package database.service;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import database.auxiliary.LogGenerator;
import po.SalePolicyPO;

public class PolicyDataServiceSerializableImpl {
	SalePolicyPO po;
	
	public PolicyDataServiceSerializableImpl(){
	}
	
	public void load(){
		try {
			File file = new File("data/policy.ser");
			if (!file.exists()) {
				file.createNewFile();
			}
			ObjectInputStream oiStream = new ObjectInputStream(
					new FileInputStream(file));
			SalePolicyPO epo; 
			if ((epo = (SalePolicyPO) oiStream.readObject()) != null) {
				this.po=epo;
			}
			LogGenerator.log("Policy data load succeed");
		} catch (EOFException e) {
			save();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void save(){
		try {
			FileOutputStream fos = new FileOutputStream("data/policy.ser");
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(po);
			oos.writeObject(null);
			LogGenerator.log("policy data save succeed");
		} catch (FileNotFoundException e) {
			System.out.println("File found failed!");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void update(SalePolicyPO epo){
		po=epo;
		LogGenerator.log("Policy update: " + po);
	}

	public SalePolicyPO getInstantPolicy() {
		return this.po;
	}	
}
